#define _GNU_SOURCE 
#define MAX 10240

#include "../include/head.h"
#include "../include/client.h"

int recvCycle(int sockFd, void *buf, int totalLen);

struct sockaddr_in addrInit(char *ipstr, char *host);
int addNewfd(int fd, int epfd);     //将fd加入到epfd中
int chatFunc(int epfd, int sockFd);//利用TCP和服务器通信

int main(int argc,char*argv[])
{
    int ret = 0;
    ARGS_CHECK(argc, 3);

    struct sockaddr_in serAddr = addrInit(argv[1], argv[2]);
    int sockFd = socket(AF_INET, SOCK_STREAM, 0);
    ERROR_CHECK(sockFd, -1, "socket");

    ret = connect(sockFd, (struct sockaddr*)&serAddr, sizeof(serAddr));
    ERROR_CHECK(ret, -1, "connect");

    //连接之后开始登录
    ret = clientLogin(sockFd);
    if (0 == ret){
        //登录失败
    }

    int epfd = epoll_create(1); //创建一个epoll描述符
    ERROR_CHECK(epfd, -1, "epoll_create");

    //将要监听的事件加入到epfd中
    ret = addNewfd(STDIN_FILENO, epfd);
    ERROR_CHECK(ret, -1, "addNewfd");
    ret = addNewfd(sockFd, epfd);
    ERROR_CHECK(ret, -1, "addNewfd");

    clientCMD(sockFd);

    return 0;
}

struct sockaddr_in addrInit(char *ipstr, char *host){
    //初始化sockaddr_in结构体
    struct sockaddr_in serAddr;
    memset(&serAddr, 0, sizeof(serAddr));
    serAddr.sin_family = AF_INET;
    serAddr.sin_addr.s_addr = inet_addr(ipstr);
    serAddr.sin_port = htons(atoi(host));
    return serAddr;
}

int addNewfd(int newfd, int epfd){
    //将newfd加入到epfd中，成功返回epfd，失败返回-1
    struct epoll_event event;
    memset(&event, 0, sizeof(event));
    event.events = EPOLLIN; //监听写事件
    event.data.fd = newfd;

    int ret = epoll_ctl(epfd, EPOLL_CTL_ADD, newfd, &event);
    ERROR_CHECK(ret, -1, "epoll_ctl");
    return epfd;
}
